package jobs.job3.classloaderdemo.server.zkutil;

import java.util.ArrayList;
import java.util.List;

//用于访问zookeeper 获取当前可用的计算节点列表
public class ZkClient {
    org.I0Itec.zkclient.ZkClient zkClient;
    List<String> serverInfos;
    String rootPath = "/calculationNodes";

    public void connectZk() {
        zkClient = new org.I0Itec.zkclient.ZkClient("localhost:2181");
        List<String> children = zkClient.getChildren(rootPath);
        parseServerInfo(children);
        zkClient.subscribeChildChanges(rootPath, (path, list) -> {
            parseServerInfo(list);
            System.out.println("服务列表 " + path + " 发生改变: " + serverInfos);
        });
    }

//    同步锁
    private synchronized void parseServerInfo(List<String> children) {
        List<String> infos = new ArrayList<String>();
        for (String child : children) infos.add(zkClient.readData(rootPath + "/" + child).toString());
        serverInfos = infos;
    }

    public synchronized List<String> getServerInfos() {
        System.out.println(" 通过zookeeper获取到计算节点列表为: " + serverInfos);
        return new ArrayList<>(serverInfos);
    }
}
